package com.byit.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.byit.builder.MapBuilder;
import com.byit.constant.DefaultValue;
import com.byit.domain.SysUser;
import com.byit.domain.SysUserRole;
import com.byit.enums.PromptInfo;
import com.byit.msg.MessageResult;
import com.byit.service.ISysUserRoleService;
import com.byit.service.ISysUserService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.PasswordUtil;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author wangx
 * @since 2018-12-11
 */
@RestController
@RequestMapping("/api/sys/sysUser")
public class SysUserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    /**
     * 插入用户数据
     *
     * @param session
     * @param user
     * @return
     */
    @PostMapping("/save")
    public Object insertUser(HttpSession session, SysUser user) {
        Long userId = SessionHelper.getUserId(session);
        Long companyId = SessionHelper.getCompanyId(session);
        try {
            if (null == user) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }
            if (StringUtil.isEmpty(user.getLoginName())) {
                return MessageResult.warpper(PromptInfo.ERROR_ACCOUNT_NOT_NULL);
            }
            //// 判断用户名是否已经在数据库中存在
            if (null == user.getId() && sysUserService.selectUserByUserName(user.getLoginName())) {
                return MessageResult.warpper(PromptInfo.ACCOUNT_IS_EXISTS);
            }
            //// 加密用户密码
            String password = PasswordUtil.pwdEncryptTwo("abc123456");
            user.setPassword(password);
            user.setCreateTime(new Date());
            user.setOperationId(userId);
            if (null == user.getCompanyId()) {
                user.setCompanyId(companyId);
            }
            sysUserService.insert(user);
            String roles = user.getRoles();
            if (!StringUtil.isEmpty(roles)) {
                List<Long> roleIds = StringUtil.splitLong(roles, ",");
                List<SysUserRole> list = new ArrayList<>();
                SysUserRole userRole = null;
                for (Long id : roleIds) {
                    userRole = new SysUserRole();
                    userRole.setRoleId(id);
                    userRole.setUserId(user.getId());
                    list.add(userRole);
                }
                sysUserRoleService.insertBatch(list);
            }
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 修改用户数据
     *
     * @param session
     * @param user
     * @return
     */
    @PostMapping("/update")
    public Object updateUser(HttpSession session, SysUser user) {
        Long userId = SessionHelper.getUserId(session);
        Long companyId = SessionHelper.getCompanyId(session);
        try {
            if (null == user) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }
            //// 加密用户密码
            user.setUpdateTime(new Date());
            user.setOperationId(userId);
            if (null == user.getCompanyId()) {
                user.setCompanyId(companyId);
            }
            sysUserService.updateById(user);
            String roles = user.getRoles();
            if (!StringUtil.isEmpty(roles)) {
                sysUserRoleService.deleteByMap(MapBuilder.newMap(1).setParam("user_id", user.getId()).ok());
                List<Long> roleIds = StringUtil.splitLong(roles, ",");
                List<SysUserRole> list = new ArrayList<>();
                SysUserRole userRole = null;
                for (Long id : roleIds) {
                    userRole = new SysUserRole();
                    userRole.setRoleId(id);
                    userRole.setUserId(user.getId());
                    list.add(userRole);
                }
                sysUserRoleService.insertBatch(list);
            }
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 那条件查询所有用户信息
     *
     * @param session
     * @param phone
     * @param userName
     * @param status
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public Object selectUserList(HttpSession session, @RequestParam(value = "phone", defaultValue = "") String phone,
                                 @RequestParam(value = "userName", defaultValue = "") String userName,
                                 @RequestParam(value = "status", defaultValue = "-1") Integer status,
                                 @RequestParam(value = "companyId", defaultValue = "") Long companyId,
                                 @RequestParam(value = "page", defaultValue = DefaultValue.PAGE_FIRST) int page,
                                 @RequestParam(value = "limit", defaultValue = DefaultValue.PAGE_SIZE) int limit) {

        Long cid = SessionHelper.getCompanyId(session);
        if (null == cid || cid.compareTo(1L) != 0) {
            companyId = cid;
        }
        Page<SysUser> pageInfo = new Page<>(page, limit);
        Map<String, Object> params = MapBuilder.newMap(4).setParam("phone", phone).setParam("status", status).setParam("companyId", companyId).ok();
        if (null != userName && !"".equals(userName)) {
            params.put("userName", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(userName) + "%");
        }
        Page<JSONObject> result = sysUserService.selectUserList(pageInfo, params);
        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, result);
    }

    /**
     * 按照用户标识查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/selectById/{id}")
    public Object selectUserById(@PathVariable("id") Long id) {
        SysUser sysUser = sysUserService.selectById(id);
        return MessageResult.success(sysUser);
    }

    /**
     * 修改当前登录用户的密码
     *
     * @param session
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @PostMapping("/updatePw")
    public Object updateUserpwById(HttpSession session,
                                   @RequestParam(value = "oldPassword") String oldPassword,
                                   @RequestParam(value = "newPassword") String newPassword) {
        SysUser user = SessionHelper.getUser(session);
        String oldPw = PasswordUtil.pwdEncryptTwo(oldPassword);
        if (!oldPw.equals(user.getPassword())) {
            return MessageResult.error(PromptInfo.ERROR_OLD_PASSWORD_NOT_MATCH);
        }
        String newPw = PasswordUtil.pwdEncryptTwo(newPassword);
        Map<String, Object> params = MapBuilder.newMap(2).setParam("id", user.getId()).setParam("pw", newPw).ok();
        sysUserService.updateUserpwById(params);

        return MessageResult.success();
    }

    /**
     * 获取当前登录用户信息
     *
     * @return
     */
    @GetMapping("/selectUser")
    public Object selectUserById(HttpSession session) {
        Long userId = SessionHelper.getUserId(session);
        SysUser sysUser = sysUserService.selectById(userId);
        return MessageResult.success(sysUser);
    }

    /**
     * 重置密码
     *
     * @return
     */
    @PostMapping("/resetPwd")
    public Object resetPwd(HttpSession session) {
        SysUser user = SessionHelper.getUser(session);
        String newPw = PasswordUtil.pwdEncryptTwo("abc123456");
        Map<String, Object> params = MapBuilder.newMap(2).setParam("id", user.getId()).setParam("pw", newPw).ok();
        sysUserService.updateUserpwById(params);

        return MessageResult.success();
    }

    /**
     * 逻辑删除用户信息
     *
     * @param session
     * @param ids
     * @return
     */
    @PostMapping("/delete")
    public Object delUserByIds(HttpSession session, @RequestParam("ids") String ids) {
        Long userId = SessionHelper.getUserId(session);
        List<Long> idList = StringUtil.splitLong(ids, ",");

        if (0 == idList.size()) {
            return MessageResult.error(PromptInfo.ERROR_DELETE_NOT_SELECT);
        }

        Map<String, Object> map = MapBuilder.newMap(3).setParam("updateTime", new Date()).setParam("operId", userId).ok();
        sysUserService.deleteBatchIds(idList);

        sysUserRoleService.deleteByUserIds(idList);

        return MessageResult.success();
    }

}
